//
//  SFOAuthViewController.swift
//  SFWeiBo
//
//  Created by 孙凡 on 16/4/10.
//  Copyright © 2016年 Edward. All rights reserved.
//

import UIKit
import SVProgressHUD

//appkey
let SF_APPKEY = "1498864782"
//回调页面
let SF_REDIRECT = "http://dx2.78land.com"
//App Secret 
let SF_APPSECRET = "44143b8bccd209f09c64642088fa6905"

//路径
let filePath: String = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")


class SFOAuthViewController: UIViewController,UIWebViewDelegate {

    //https://api.weibo.com/oauth2/authorize?client_id=1498864782&redirect_uri=http://dx2.78land.com

    private lazy var OAuth: NSURL = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(SF_APPKEY)&redirect_uri=\(SF_REDIRECT)")!


    override func loadView() {

        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()

        let request = NSURLRequest(URL: OAuth)

        webView.loadRequest(request)
    }



    private func setupUI(){



        self.navigationItem.title = "新浪微博"

        self.navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: nil, title: "关闭", target: self, SEL: #selector(SFOAuthViewController.close))

        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: nil, title: "自动填充", target: self, SEL: #selector(SFOAuthViewController.autoFill))

    }

    //点击关闭
    @objc private func close(){

        dismissViewControllerAnimated(true, completion: nil)

    }
    //点击自动填充
    @objc private func autoFill(){

//        print("点击了自动填充")

        let account = "18201151151"
        let secret = "sf1215225"

        //document.getElementById('userId').value='18754734433';document.getElementById('passwd').value='sf1215225'

        let string:String = "document.getElementById('userId').value='\(account)';document.getElementById('passwd').value='\(secret)'"

        webView.stringByEvaluatingJavaScriptFromString(string)

    }


    //MARK: - 懒加载控件

     lazy var webView :UIWebView = {

        let webView = UIWebView()

        webView.delegate = self


        return webView

    }()


}

extension SFOAuthViewController{

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{

//        print(request.URL?.absoluteString)

        // 判断url是否为空
        guard let url = request.URL else {

            return true
        }

        //判断当前加载的页面是否为回调页(判断头是否为回调页的统一资源定位符)
        if url.absoluteString.hasPrefix(SF_REDIRECT) {

            //截取code后边的数字

            //query是只第一个问好后边的内容,我们要找问号后边code=后边的内容
            let query = url.query!
            //拿到code授权码
            let code = query.substringFromIndex("code=".endIndex)

            //拿到授权码后要求获取accessToken
//            print(code)

            SFUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code: code, callBack: { (success, error) in

                if success == false {

                    SVProgressHUD.showErrorWithStatus("\(error)")
                }

                //MARK: - 成功跳转界面
//                SVProgressHUD.showErrorWithStatus("成功")
                
//                self.presentViewController(SFWelcomeViewController(), animated: true, completion: nil)

                self.dismissViewControllerAnimated(false, completion: { 

//                    let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
//
//                    delegate.window?.rootViewController = SFWelcomeViewController()

                    //用通知进行跳转
                    NSNotificationCenter.defaultCenter().postNotificationName(SFSwitchRootViewControllerNotification, object: self)

                })


            })


            //拿到该拿的东西后就不用给用户展示回调页了
            return true

        }


        return true
    }

}

//    private func  loadAccessToken(code code:String){
//
//        // 请求地址
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//
//        /**
//         必选	类型及范围	说明
//         client_id	true	string	申请应用时分配的AppKey。
//         client_secret	true	string	申请应用时分配的AppSecret。
//         grant_type	true	string	请求的类型，填写authorization_code
//
//         grant_type为authorization_code时
//         必选	类型及范围	说明
//         code	true	string	调用authorize获得的code值。
//         redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
//         */
//
//        //拼接参数
//        let paramters = [
//            "client_id": SF_APPKEY,
//            "client_secret": SF_APPSECRET,
//            "grant_type": "authorization_code",
//            "code": code,
//            "redirect_uri": SF_REDIRECT
//        ]
//
//        SFNetworkTools.sharedTools.request(SFRequestMethod.POST, URLString: urlString, parameters: paramters) { (responseObjct, error) in
//
//            if error != nil{
//
//                print("error----------\(error)")
//
//                return
//            }
//
//            //进行字典转模型,保存用户的信息
////            print("正确........\(responseObjct)")
//
//            /**
//             "access_token" = "2.00BCAP3E7MF8dBe0122181a67nLRHD";
//             "expires_in" = 157679999;  过期时间(秒)
//             "remind_in" = 157679999;
//             uid = 3993185765;      当前用户的ID
//             */
//
//            let dict: [String: AnyObject] = responseObjct as! [String: AnyObject]
//
////            print("sssssssssssssssssss\(dict)")
//
//
//            let account = SFUserAccount(dict: dict)
//
////            print("sssssssssssssss\(account)sssssssssssss")
//
//            /**
//             根据
//             access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
//             uid            false	int64	需要查询的用户ID。
//             screen_name	false	string	需要查询的用户昵称。
//
//             获取用户信息
//             */
//            self.loadUserInfo(account)
//
//        }
//
//
//    }
//
//
//    private func loadUserInfo(account: SFUserAccount){
//
//        //请求地址
//        let urlString = "https://api.weibo.com/2/users/show.json"
//
////        let urlString1 = "https://api.weibo.com/2/users/show.json?access_token=2.00BCAP3E7MF8dBe0122181a67nLRHD&uid=3993185765"
//
//        //判断参数
//        guard let accessToken = account.access_token else {
//            print("参数不够")
//            return
//        }
//
//        let uid = account.uid
//        if uid == 0{
//            print("参数不够")
//            return
//
//        }
//
//        //请求参数
//        let paramters :[String: AnyObject] = ["access_token": accessToken, "uid": uid]
//
//        SFNetworkTools.sharedTools.request(SFRequestMethod.GET, URLString: urlString, parameters: paramters) { (responseObjct, error) in
//
//            if error != nil {
//
//                print(error)
//
//                SVProgressHUD.showErrorWithStatus("个人信息请求失败")
//
//                return
//            }
//
//            //请求成功后给模型赋值
////            print(responseObjct)
//            account.screen_name = responseObjct!["screen_name"] as? String
//            account.avatar_large = responseObjct!["avatar_large"] as? String
//
//
//            //保存用户登录的模型,以便于下次登录(归档)
//
//            NSKeyedArchiver.archiveRootObject(account, toFile: filePath)
//
//        }
//
//
//    }





